import xlwt
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from allpairspy import AllPairs

import json  # 做一个公共的字典，然后每个函数之后都默认加上这个字典。


def globaldict(request):
    userimg = str(request.session["user"]) + '.png'
    res = {"username": request.session["user"], "userimg": userimg}
    return res


# 正交鞠躬页面
def zhengjiao(request):
    return render(request, 'welcome.html', {"whichHTML": "zhengjiao.html", "oid": request.session['user'], **globaldict(request)})

#  运行
def zhengjiao_play(request):
    end_values = request.GET["end_values"].split(",")
    # print(end_values)
    new_values = [i.split("/") for i in end_values]
    # print(new_values)
    res=[]
    for i in AllPairs(new_values):
        # print(i)
        res.append(i)
    d = {"res":res}
    return HttpResponse(json.dumps(d),content_type='application/json')

# 导出excel
def zhengjiao_excel(request):
    end_keys = request.GET['end_keys'].split(',')
    end_values = request.GET['end_values'].split(',')
    new_values = [i.split('/') for i in end_values]
    res = []
    for i in AllPairs(new_values):
        res.append(i)
    # 先创建
    book = xlwt.Workbook(encoding='utf-8') # 创建excel
    sheet = book.add_sheet("正交结果") # 创建sheet页
    for i in range(len(res)):
        case_index = '用例:'+str(i+1) # 用例序号
        hb = list(zip(end_keys,res[i])) #把key和value进行合并
        case = ','.join([':'.join(list(i)) for i in hb]) #进行格式化，便于阅读
        sheet.write(i,0,case_index)  # 写入，i为行，0为第一例
        sheet.write(i, 1, case)  # 写入，i为行，1为第二例
    book.save('api_test/static/tmp_zhengjiao.xls') #保存

    return HttpResponse('')


#  json字符串对比，利用反射获取结果和清理

class Cmp_json():
    json_res = []

    def compare_json_data(self,A, B, xpath='.'):

        if isinstance(A, list) and isinstance(B, list):
            for i in range(len(A)):
                try:
                    self.compare_json_data(A[i], B[i], xpath + '[%s]' % str(i))
                except:
                    self.json_res.append('▇▇▇▇▇ A中的%s[%s]未在B中找到' % (xpath, i))
        if isinstance(A, dict) and isinstance(B, dict):
            for i in A:
                try:
                    B[i]
                except:
                    self.json_res.append('▇▇▇▇▇ A中的%s/%s 未在B中找到' % (xpath, i))
                    continue
                if not (isinstance(A.get(i), (list, dict)) or isinstance(B.get(i), (list, dict))):
                    if type(A.get(i)) != type(B.get(i)):
                        self.json_res.append('▇▇▇▇▇ 类型不同参数在[A]中的绝对路径:  %s/%s  ►►► A is %s, B is %s ' % (
                        xpath, i, type(A.get(i)), type(B.get(i))))
                    elif A.get(i) != B.get(i):
                        self.json_res.append('▇▇▇▇▇ 仅内容不同参数在[A]中的绝对路径:  %s/%s  ►►► A is %s, B is %s ' % (xpath, i, A.get(i), B.get(i)))
                    continue
                self.compare_json_data(A.get(i), B.get(i), xpath + '/' + str(i))
            return
        if type(A) != type(B):
            self.json_res.append('▇▇▇▇▇ 类型不同参数在[A]中的绝对路径:  %s  ►►► A is %s, B is %s ' % (xpath, type(A), type(B)))
        elif A != B and type(A) is not list:
            self.json_res.append('▇▇▇▇▇ 仅内容不同参数在[A]中的绝对路径:  %s  ►►► A is %s, B is %s ' % (xpath, A, B))

cj = Cmp_json()